﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Services.Exceptions;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class BanEmails : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            Page.CloseMessage(lblMsg);
        }

        protected void BtnDeleteClick(object sender, EventArgs e)
        {
            if (Request.Form["chkItem"] == null) return;

            string selectedItems = Request.Form["chkItem"];
            string[] selectedItemIds = selectedItems.Split(',');
            foreach (Guid itId in selectedItemIds.Select(t => new Guid(t))) LoggerEmailServices.Delete(itId);

            gridData.DataBind();
            udpGrid.DataBind();
        }

        protected void BtnBanEmailClick(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            try
            {
                var loggerEmail = new LoggerEmail { Email = txtEmail.Text, Type = EmailType.Lock };
                LoggerEmailServices.SaveOrUpdate(loggerEmail);

                Page.DisplayMessage(lblMsg, "Ban email đã thành công!", MessageType.Success);

                gridData.DataBind();
                udpGrid.DataBind();
            }
            catch (ObjectAlreadyExistException ex)
            {
                Page.DisplayMessage(lblMsg, "Bạn đã ban email này rồi!", MessageType.Warning);
                Logger.Debug(ex.Message);
            }
            catch (Exception exception)
            {
                Logger.Debug(exception.Message);
                Page.DisplayMessage(lblMsg, "Ban email không thành công!", MessageType.Error);
            }
        }

        protected void GridDataItemCommand(object sender, CommandEventArgs e)
        {
            string commandName = e.CommandName;
            string commandArgument = e.CommandArgument.ToString();

            if (commandArgument == string.Empty) return;
            var guidId = new Guid(commandArgument);

            if ("Delete".Equals(commandName)) LoggerEmailServices.Delete(guidId);
            udpGrid.DataBind();
        }


        protected void DdlEmailTypeSelectedIndexChanged(object sender, EventArgs e)
        {
            bool isBanEmail = ddlEmailType.SelectedValue.Equals("1");
            lblLockEmail.Visible = txtEmail.Visible = btnBanEmail.Visible = rfvEmail.Visible = revEmail.Visible = isBanEmail;

            btnDelete.Text = isBanEmail ? "Hủy ban" : "Chọn xóa";
            btnDelete.ToolTip = isBanEmail ? "Hủy ban những email đã đánh dấu!" : "Xóa những tin đã đánh dấu!";
        }
    }
}
